#include "R2.h"

pq ready, blocked, suspended, suspended_blocked;

void find_pcb(char pname) {

	pqn *temp;

	// search ready
	
	temp = ready.root;
	
	if (!pq_is_empty(ready))
	
		do {
		
			if (strcmp(temp->data->name, pname) == 0) return temp;
			
	} while (temp != NULL);
	
	// search blocked
	
	if (!pq_is_empty(blocked))
	
		do {
		
			if (strcmp(temp->data->name, pname) == 0) return temp;
			
	} while (temp != NULL);
		
	return NULL;

}

void set_priority(int argc, char **arv) {

	pcb *temp;
	int priority = atoi(argv[1]);

	if (argc != 2) printf("Invalid number of arguments. Usage: set_priority process_name priority.\n");

	temp = find_pcb(argv[0]);
	
	if (temp == NULL) {
	
		printf("Process does not exist.");
		return;
		
	}
	
	if (priority < -127 || priority > 128) {
	
		printf("Priority should be in the range -127 to 128\n");
		return;
	
	}
	
	temp->priority = priority;	
	remove_pcb(temp);
	if (temp->state == READY)
	insert_pcb(READY, temp);
	if (temp->state == BLOCKED)
	insert_pcb(BLOCKED, temp);
	
}

void show_pcb (int argc, char **argv) {

	if (argc != 1) printf("Invalid number of arguments. Usage: show_pcb process_name.\n");
	pcb *n = find_pcb(arg[0]);
	printf("Name: %s, Class: %d, Size: %d, Priority: %d, State: %d\n", n->name, n->class, n->memory_size, n->priority, n->state);

}

void show_all(int argc, char **argv) {

	show_ready();
	show_blocked();

}

void show_ready(int argc, char **argv) {

	pqn *temp;

	if (!pq_is_empty(ready)) {

		printf("Displaying processes in ready queue:\n\n");

		temp = ready.root;

		do {

			printf("Name: %s, Class: %d, Size: %d, Priority: %d, State: %d\n", n->data->name, n->data->class, n->data->memory_size, n->data->priority, n->data->state);
			temp = temp.right;

		} while (temp != NULL);	

	} else printf("No processes in ready queue.");

}

void show_blocked() {

	pqn *temp;

	if (!pq_is_empty(blocked)) {

		printf("Displaying processes in blocked queue:");
	
		temp = blocked.root;

		do {
		
			printf("Name: %s, Class: %d, Size: %d, Priority: %d, State: %d\n", n->data->name, n->data->class, n->data->memory_size, n->data->priority, n->data->state);
			temp = temp.right;

		} while (temp != NULL);	

	} else printf("No processes in blocked queue.");

}
